import {
  WeaEchart,
} from 'ecCom'

import {
  Row,
  Col,
  message,
  Tooltip,
} from 'antd'

import React from 'react';
import {
  i18n
} from '../../public/i18n';

import {
  jumpToHrmDept
} from '../../util/pulic-func'

class BarChart extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: i18n.button.saveAsImage(),
      optionL: {},
      optionR: {},
    }
  }

  componentDidUpdate() {
    if (this.refs.echart1) this.refs.echart1.paint();
    if (this.refs.echart2) this.refs.echart2.paint();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.winWidth !== nextProps.winWidth) {
      if (this.refs.echart1) this.refs.echart1.chart.resize();
      if (this.refs.echart2) this.refs.echart2.chart.resize();
    }

    if (this.props.option !== nextProps.option) {
      if (!this.isEmptyObject(nextProps.gridData) && !this.isEmptyObject(nextProps.option[0]) && !this.isEmptyObject(nextProps.option[1])) {
        this.setBarWidth(nextProps);
      }
    }
  }

  isEmptyObject(obj) {
    for (let key in obj) {
      return false;
    }
    return true;
  }

  setBarWidth(nextProps) {
    const {
      yAxisScaleMaxLen
    } = this.props;

    if (!this.refs.echart1) {
      return;
    }
    let h = 340;
    let data = nextProps.gridData;
    let opt = nextProps.option[0];
    let l = yAxisScaleMaxLen || 10;
    let b;
    let t;
    if (data.bottom) {
      b = parseInt(data.bottom) / 100 * h;
    } else {
      b = 60;
    }
    if (data.top) {
      t = parseInt(data.top) / 100 * h;
    } else {
      t = 60;
    }
    let s = (h - (b + t)) / l;

    nextProps.option[0].series[0].barWidth = s * 0.9;
    nextProps.option[1].series[0].barWidth = s * 0.9;

    this.setState({
      optionL: nextProps.option[0],
      optionR: nextProps.option[1]
    })

  }

  getDOM(tag, isChartsShow, chartTitle) {
    const {
      setVisible,
      linkStyle
    } = this.props;
    const {
      text
    } = this.state;
    return (
      <div style={{position: 'absolute', right: 0}}>
  				      <div style={{float: 'left', padding: '10px 0'} }>
          		      { tag == 'left' ? <a onClick={() => setVisible('1', true)} className={linkStyle}>{i18n.button.more()}</a> : ''}	
        		    </div>
        		    <div style={{float: 'left', padding: '8px 20px 10px 10px', fontSize: 16}}> 
        		         { isChartsShow ?  <a onClick={() => this.download(tag, chartTitle)} className={linkStyle} title={i18n.button.saveAsImage()}>
                                            <i className='icon-coms-download2' /> 
        		                           </a>
        		                        :  <a onClick={() => {message.info(i18n.message.dataNone())}} className={linkStyle} title={i18n.button.saveAsImage()}>
                                            <i className='icon-coms-download2' />
        		                           </a>
        		      }
        		    </div>
  			    </div>
    )
  }

  download(tag, chartTitle) {
    let cvs = document.getElementsByTagName('canvas');
    if (tag == 'left') {
      this.downloadCvs2Img(cvs[0], chartTitle);
    } else {
      this.downloadCvs2Img(cvs[1], chartTitle);
    }
  }

  downloadCvs2Img(cvs, chartTitle) {
    let $a = document.createElement('a');
    $a.download = chartTitle + '.jpg';
    $a.target = '_blank';
    let url;
    if (cvs) {
      url = cvs.toDataURL("image/jpg");
    } else {
      message.info(i18n.message.dataNone());
    }

    if (url) $a.href = url;

    if (typeof MouseEvent === 'function') {
      var evt = new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: false
      });
      $a.dispatchEvent(evt);
    } else {
      if (window.navigator.msSaveOrOpenBlob) {
        var bstr = atob(url.split(',')[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        var blob = new Blob([u8arr]);
        window.navigator.msSaveOrOpenBlob(blob, chartTitle + '.jpg');
      } else {
        var html = '' +
          '<body style="margin:0;">' +
          '<img src="' + url + '" style="max-width:100%;" title="" />' +
          '</body>';
        var tab = window.open();
        tab.document.write(html);
      }
    }
  }

  chartAction(chart, idy) {
    chart.off('click');
    chart.on('click', (params) => this.handleClick(params, idy));
  }

  handleClick(params, idy) {
    const {
      ids,
      yAxisData,
      linkList,
      setVisible
    } = this.props;

    if (params.componentType == 'yAxis') {
      let anid = params.event.target.anid;
      if (!anid) {
        return
      }
      let index = anid.split('_')[1];
      jumpToHrmDept(ids[index]);
    }

    if (idy == 'left' && params.componentType == 'series') {
      const {dataIndex} = params;
      const dept = {
        id:ids[dataIndex],
        name:yAxisData[dataIndex]
      }
      setVisible('2', true, dept);
    }

    if (idy == 'right' && params.componentType == 'series') {
      setVisible('3', true, params.name);
    }
  }

  render() {
    const {
      chartTitle,
      isChartsShow,
      winWidth
    } = this.props;
    const {
      optionL,
      optionR
    } = this.state;

    return (
      <div>
        		    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@o3nz8o`}>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@x13p4w`} span={12}>
                        <div style={{height: 400, margin: '8px 8px 8px 16px', border: '1px solid #DDD', borderRadius: 3}}>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@v5izou`}>
                              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3def2v`}>
                                <div style={{height: 40, backgroundColor: '#F9F9F9', position: 'relative'}}>
                                  <div style={{height: '100%', padding: '11px 0 12px 16px', float: 'left' }}>{chartTitle[0]}</div>
                                  <div style={{height: 50 }}>
                                     {this.getDOM('left', isChartsShow[0], chartTitle[0])} 
                                  </div>
                                </div>
                              </Col>
                            </Row>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@wzibn3`}>
                              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@nr376a`}>
                                {isChartsShow[0] ? <div style={{height: 340}}>
                                                      <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@wec1sj`} ref="echart1" option={optionL} useDefault={false} chartAction={ (chart) => this.chartAction(chart, 'left')}/>
                                                    </div>
                                                  : <div style={{position: 'absolute', top: 100, left: '50%', marginLeft: -24, textAlign: 'center'}}>
                                                      <div style={{fontSize: 50}}><i className='icon-coms-blank'></i></div>
                                                      <div style={{fontSize: 15, color:'#B2B2B2'}}>{i18n.message.dataNone()}</div>
                                                   </div>
                                }
                              </Col>
                            </Row>
                        </div> 
                    </Col>
                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8dvkjx`} span={12}>
                        <div style={{height: 400, margin: '8px 16px 8px 8px', border: '1px solid #DDD',borderRadius: 3}}> 
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@5lv4gs`}>
                              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@64pa1t`}>
                                <div style={{height: 40, backgroundColor: '#F9F9F9', position: 'relative'}}>
                                  <div style={{height: '100%', padding: '11px 0 12px 16px', float: 'left' }}>{chartTitle[1]}</div>
                                  <div style={{ height: 50 }}>
                                     {this.getDOM('right', isChartsShow[1], chartTitle[1])} 
                                  </div>
                                </div>
                              </Col>
                            </Row>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@btr5lt`}>
                              <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@i6xciu`}>
                                {isChartsShow[1] ? <div style={{height: 340}}>
                                                      <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@vljy8j`} ref="echart2" option={optionR} useDefault={false} chartAction={ (chart) => this.chartAction(chart, 'right')}/>
                                                    </div>
                                                 : <div style={{position: 'absolute', top: 100, left: '50%', marginLeft: -24, textAlign: 'center'}}>
                                                     <div style={{fontSize: 50}}><i className='icon-coms-blank'></i></div>
                                                     <div style={{fontSize: 15, color:'#B2B2B2'}}>{i18n.message.dataNone()}</div>
                                                   </div>}   
                              </Col>
                            </Row>
                        </div>
                    </Col>
                </Row>
        	  </div>
    )
  }
}

export default BarChart